home *** CD-ROM | disk | FTP | other *** search
/ Amiga Games Extra 1996 September / Amiga Games Extra CD-ROM 9-1996.iso / userbox / publicdomain / vim-4.2 / src / unix.c < prev    next >
C/C++ Source or Header  |  1996-06-16  |  61KB  |  2,883 lines

  1. /* vi:set ts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved        by Bram Moolenaar
  4.  *                OS/2 port by Paul Slootman
  5.  *
  6.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  7.  * Do ":help credits" in Vim to see a list of people who contributed.
  8.  */
  9.  
  10. /*
  11.  * unix.c -- code for all flavors of Unix (BSD, SYSV, SVR4, POSIX, ...)
  12.  *           Also for OS/2, using the excellent EMX package!!!
  13.  *
  14.  * A lot of this file was originally written by Juergen Weigert and later
  15.  * changed beyond recognition.
  16.  */
  17.  
  18. /*
  19.  * Some systems have a prototype for select() that has (int *) instead of
  20.  * (fd_set *), which is wrong. This define removes that prototype. We include
  21.  * our own prototype in osdef.h.
  22.  */
  23. #define select select_declared_wrong
  24.  
  25. #include "vim.h"
  26. #include "globals.h"
  27. #include "option.h"
  28. #include "proto.h"
  29.  
  30. #ifdef HAVE_FCNTL_H
  31. # include <fcntl.h>
  32. #endif
  33.  
  34. #include "unixunix.h"        /* unix includes for unix.c only */
  35.  
  36. /*
  37.  * Use this prototype for select, some include files have a wrong prototype
  38.  */
  39. #undef select
  40.  
  41. #if defined(HAVE_SELECT)
  42. extern int   select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
  43. #endif
  44.  
  45. /*
  46.  * end of autoconf section. To be extended...
  47.  */
  48.  
  49. /* Are the following #ifdefs still required? And why? Is that for X11? */
  50.  
  51. #if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
  52. # ifdef SIGWINCH
  53. #  undef SIGWINCH
  54. # endif
  55. # ifdef TIOCGWINSZ
  56. #  undef TIOCGWINSZ
  57. # endif
  58. #endif
  59.  
  60. #if defined(SIGWINDOW) && !defined(SIGWINCH)    /* hpux 9.01 has it */
  61. # define SIGWINCH SIGWINDOW
  62. #endif
  63.  
  64. #if defined(HAVE_X11) && defined(WANT_X11)
  65. # include <X11/Xlib.h>
  66. # include <X11/Xutil.h>
  67. # include <X11/Xatom.h>
  68.  
  69. Window        x11_window = 0;
  70. Display        *x11_display = NULL;
  71. int            got_x_error = FALSE;
  72.  
  73. static int    get_x11_windis __ARGS((void));
  74. static void set_x11_title __ARGS((char_u *));
  75. static void set_x11_icon __ARGS((char_u *));
  76. #endif
  77.  
  78. static int get_x11_title __ARGS((int));
  79. static int get_x11_icon __ARGS((int));
  80.  
  81. static void may_core_dump __ARGS((void));
  82.  
  83. static int    Read __ARGS((char_u *, long));
  84. static int    WaitForChar __ARGS((long));
  85. static int    RealWaitForChar __ARGS((int, long));
  86. static void fill_inbuf __ARGS((int));
  87.  
  88. #if defined(SIGWINCH)
  89. static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
  90. #endif
  91. #if defined(SIGALRM) && defined(HAVE_X11) && defined(WANT_X11)
  92. static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
  93. #endif
  94. static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
  95.  
  96. static void catch_signals __ARGS((RETSIGTYPE (*func)()));
  97. #ifndef __EMX__
  98. static int    have_wildcard __ARGS((int, char_u **));
  99. static int    have_dollars __ARGS((int, char_u **));
  100. #endif
  101.  
  102. static int        do_resize = FALSE;
  103. static char_u    *oldtitle = NULL;
  104. static char_u    *fixedtitle = (char_u *)"Thanks for flying Vim";
  105. static char_u    *oldicon = NULL;
  106. #ifndef __EMX__
  107. static char_u    *extra_shell_arg = NULL;
  108. static int        show_shell_mess = TRUE;
  109. #endif
  110. static int        core_dump = FALSE;            /* core dump in mch_windexit() */
  111.  
  112. #ifdef SYS_SIGLIST_DECLARED
  113. /*
  114.  * I have seen 
  115.  *     extern char *_sys_siglist[NSIG];
  116.  * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
  117.  * that describe the signals. That is nearly what we want here.  But
  118.  * autoconf does only check for sys_siglist (without the underscore), I
  119.  * do not want to change everything today.... jw.
  120.  * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
  121.  */
  122. #endif
  123.  
  124. static struct
  125. {
  126.     int        sig;        /* Signal number, eg. SIGSEGV etc */
  127.     char    *name;        /* Signal name (not char_u!). */
  128.     int        dump;        /* Should this signal cause a core dump? */
  129. } signal_info[] =
  130. {
  131. #ifdef SIGHUP
  132.     {SIGHUP,        "HUP",        FALSE},
  133. #endif
  134. #ifdef SIGINT
  135.     {SIGINT,        "INT",        FALSE},
  136. #endif
  137. #ifdef SIGQUIT
  138.     {SIGQUIT,        "QUIT",        TRUE},
  139. #endif
  140. #ifdef SIGILL
  141.     {SIGILL,        "ILL",        TRUE},
  142. #endif
  143. #ifdef SIGTRAP
  144.     {SIGTRAP,        "TRAP",        TRUE},
  145. #endif
  146. #ifdef SIGABRT
  147.     {SIGABRT,        "ABRT",        TRUE},
  148. #endif
  149. #ifdef SIGEMT
  150.     {SIGEMT,        "EMT",        TRUE},
  151. #endif
  152. #ifdef SIGFPE
  153.     {SIGFPE,        "FPE",        TRUE},
  154. #endif
  155. #ifdef SIGBUS
  156.     {SIGBUS,        "BUS",        TRUE},
  157. #endif
  158. #ifdef SIGSEGV
  159.     {SIGSEGV,        "SEGV",        TRUE},
  160. #endif
  161. #ifdef SIGSYS
  162.     {SIGSYS,        "SYS",        TRUE},
  163. #endif
  164. #ifdef SIGALRM
  165.     {SIGALRM,        "ALRM",        FALSE},
  166. #endif
  167. #ifdef SIGTERM
  168.     {SIGTERM,        "TERM",        FALSE},
  169. #endif
  170. #ifdef SIGVTALRM
  171.     {SIGVTALRM,        "VTALRM",    FALSE},
  172. #endif
  173. #ifdef SIGPROF
  174.     {SIGPROF,        "PROF",        FALSE},
  175. #endif
  176. #ifdef SIGXCPU
  177.     {SIGXCPU,        "XCPU",        TRUE},
  178. #endif
  179. #ifdef SIGXFSZ
  180.     {SIGXFSZ,        "XFSZ",        TRUE},
  181. #endif
  182. #ifdef SIGUSR1
  183.     {SIGUSR1,        "USR1",        FALSE},
  184. #endif
  185. #ifdef SIGUSR2
  186.     {SIGUSR2,        "USR2",        FALSE},
  187. #endif
  188.     {-1,            "Unknown!",    -1}
  189. };
  190.  
  191.     void
  192. mch_write(s, len)
  193.     char_u    *s;
  194.     int        len;
  195. {
  196. #ifdef USE_GUI
  197.     if (gui.in_use && !gui.dying)
  198.     {
  199.         gui_write(s, len);
  200.         if (p_wd)
  201.             gui_mch_wait_for_chars(p_wd);
  202.     }
  203.     else
  204. #endif
  205.     {
  206.         write(1, (char *)s, len);
  207.         if (p_wd)            /* Unix is too fast, slow down a bit more */
  208.             RealWaitForChar(0, p_wd);
  209.     }
  210. }
  211.  
  212. /*
  213.  * mch_inchar(): low level input funcion.
  214.  * Get a characters from the keyboard.
  215.  * Return the number of characters that are available.
  216.  * If wtime == 0 do not wait for characters.
  217.  * If wtime == n wait a short time for characters.
  218.  * If wtime == -1 wait forever for characters.
  219.  */
  220.     int
  221. mch_inchar(buf, maxlen, wtime)
  222.     char_u    *buf;
  223.     int        maxlen;
  224.     long    wtime;            /* don't use "time", MIPS cannot handle it */
  225. {
  226.     int            len;
  227.  
  228. #ifdef USE_GUI
  229.     if (gui.in_use)
  230.     {
  231.         if (!gui_mch_wait_for_chars(wtime))
  232.             return 0;
  233.         return Read(buf, (long)maxlen);
  234.     }
  235. #endif
  236.  
  237.     if (wtime >= 0)
  238.     {
  239.         while (WaitForChar(wtime) == 0)        /* no character available */
  240.         {
  241.             if (!do_resize)            /* return if not interrupted by resize */
  242.                 return 0;
  243.             set_winsize(0, 0, FALSE);
  244.             do_resize = FALSE;
  245.         }
  246.     }
  247.     else        /* wtime == -1 */
  248.     {
  249.     /*
  250.      * If there is no character available within 'updatetime' seconds
  251.      * flush all the swap files to disk
  252.      * Also done when interrupted by SIGWINCH.
  253.      */
  254.         if (WaitForChar(p_ut) == 0)
  255.             updatescript(0);
  256.     }
  257.  
  258.     for (;;)    /* repeat until we got a character */
  259.     {
  260.         if (do_resize)        /* window changed size */
  261.         {
  262.             set_winsize(0, 0, FALSE);
  263.             do_resize = FALSE;
  264.         }
  265.         /* 
  266.          * we want to be interrupted by the winch signal
  267.          */
  268.         WaitForChar(-1L);
  269.         if (do_resize)        /* interrupted by SIGWINCHsignal */
  270.             continue;
  271.  
  272.         /*
  273.          * For some terminals we only get one character at a time.
  274.          * We want the get all available characters, so we could keep on
  275.          * trying until none is available
  276.          * For some other terminals this is quite slow, that's why we don't do
  277.          * it.
  278.          */
  279.         len = Read(buf, (long)maxlen);
  280.         if (len > 0)
  281.         {
  282. #ifdef OS2
  283.             int i;
  284.  
  285.             for (i = 0; i < len; i++)
  286.                 if (buf[i] == 0)
  287.                     buf[i] = K_NUL;
  288. #endif
  289.             return len;
  290.         }
  291.     }
  292. }
  293.  
  294. /*
  295.  * return non-zero if a character is available
  296.  */
  297.     int
  298. mch_char_avail()
  299. {
  300. #ifdef USE_GUI
  301.     if (gui.in_use)
  302.     {
  303.         gui_mch_update();
  304.         return !is_input_buf_empty();
  305.     }
  306. #endif
  307.     return WaitForChar(0L);
  308. }
  309.  
  310.     long
  311. mch_avail_mem(special)
  312.     int special;
  313. {
  314. #ifdef __EMX__
  315.     return ulimit(3, 0L);    /* always 32MB? */
  316. #else
  317.      return 0x7fffffff;        /* virtual memory eh */
  318. #endif
  319. }
  320.  
  321.     void
  322. mch_delay(msec, ignoreinput)
  323.     long        msec;
  324.     int            ignoreinput;
  325. {
  326.     if (ignoreinput)
  327. #ifndef HAVE_SELECT
  328.         poll(NULL, 0, (int)msec);
  329. #else
  330. # ifdef __EMX__
  331.     _sleep2(msec);
  332. # else
  333.     {
  334.         struct timeval tv;
  335.  
  336.         tv.tv_sec = msec / 1000;
  337.         tv.tv_usec = (msec % 1000) * 1000;
  338.         select(0, NULL, NULL, NULL, &tv);
  339.     }
  340. # endif    /* __EMX__ */
  341. #endif    /* HAVE_SELECT */
  342.     else
  343. #ifdef USE_GUI
  344.         if (gui.in_use)
  345.             gui_mch_wait_for_chars(msec);
  346.         else
  347. #endif
  348.             WaitForChar(msec);
  349. }
  350.  
  351. #if defined(SIGWINCH)
  352. /*
  353.  * We need correct potatotypes, otherwise mean compilers will barf when the
  354.  * second argument to signal() is ``wrong''.
  355.  * Let me try it with a few tricky defines from my own osdef.h  (jw).
  356.  */
  357.     static RETSIGTYPE
  358. sig_winch SIGDEFARG(sigarg)
  359. {
  360.     /* this is not required on all systems, but it doesn't hurt anybody */
  361.     signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
  362.     do_resize = TRUE;
  363.     SIGRETURN;
  364. }
  365. #endif
  366.  
  367. #if defined(SIGALRM) && defined(HAVE_X11) && defined(WANT_X11)
  368. /*
  369.  * signal function for alarm().
  370.  */
  371.     static RETSIGTYPE
  372. sig_alarm SIGDEFARG(sigarg)
  373. {
  374.     /* doesn't do anything, just to break a system call */
  375.     SIGRETURN;
  376. }
  377. #endif
  378.  
  379.     void
  380. mch_resize()
  381. {
  382.     do_resize = TRUE;
  383. }
  384.  
  385. /*
  386.  * This function handles deadly signals.
  387.  * It tries to preserve any swap file and exit properly.
  388.  * (partly from Elvis).
  389.  */
  390.     static RETSIGTYPE
  391. deathtrap SIGDEFARG(sigarg)
  392. {
  393.     static int        entered = 0;
  394. #ifdef SIGHASARG
  395.     int        i;
  396.  
  397.     for (i = 0; signal_info[i].dump != -1; i++)
  398.     {
  399.         if (sigarg == signal_info[i].sig)
  400.         {
  401.             if (signal_info[i].dump)
  402.                 core_dump = TRUE;
  403.             break;
  404.         }
  405.     }
  406. #endif
  407.  
  408.     /*
  409.      * If something goes wrong after entering here, we may get here again.
  410.      * When this happens, give a message and try to exit nicely (resetting the
  411.      * terminal mode, etc.)
  412.      * When this happens twice, just exit, don't even try to give a message,
  413.      * stack may be corrupt or something weird.
  414.      */
  415.     if (entered == 2)
  416.     {
  417.         may_core_dump();
  418.         exit(7);
  419.     }
  420.     if (entered)
  421.     {
  422.         OUTSTR("Vim: Double signal, exiting\n");
  423.         flushbuf();
  424.         getout(1);
  425.     }
  426.     ++entered;
  427.  
  428.     sprintf((char *)IObuff, "Vim: Caught %s %s\n",
  429. #ifdef SIGHASARG
  430.                     "deadly signal", signal_info[i].name);
  431. #else
  432.                     "some", "deadly signal");
  433. #endif
  434.  
  435.     preserve_exit();                /* preserve files and exit */
  436.  
  437.     SIGRETURN;
  438. }
  439.  
  440. /*
  441.  * If the machine has job control, use it to suspend the program,
  442.  * otherwise fake it by starting a new shell.
  443.  * When running the GUI iconify the window.
  444.  */
  445.     void
  446. mch_suspend()
  447. {
  448. #ifdef USE_GUI
  449.     if (gui.in_use)
  450.     {
  451.         gui_mch_iconify();
  452.         return;
  453.     }
  454. #endif
  455. #ifdef SIGTSTP
  456.     flushbuf();                /* needed to make cursor visible on some systems */
  457.     settmode(0);
  458.     flushbuf();                /* needed to disable mouse on some systems */
  459.     kill(0, SIGTSTP);        /* send ourselves a STOP signal */
  460.     
  461.     /*
  462.      * Set oldtitle to NULL, so the current title is obtained again.
  463.      */
  464.     if (oldtitle != fixedtitle)
  465.     {
  466.         vim_free(oldtitle);
  467.         oldtitle = NULL;
  468.     }
  469.     settmode(1);
  470. #else
  471.     MSG_OUTSTR("new shell started\n");
  472.     (void)call_shell(NULL, SHELL_COOKED);
  473. #endif
  474.     need_check_timestamps = TRUE;
  475. }
  476.  
  477.     void
  478. mch_windinit()
  479. {
  480.     Columns = 80;
  481.     Rows = 24;
  482.  
  483.     flushbuf();
  484.  
  485.     (void)mch_get_winsize();
  486.  
  487. #if defined(SIGWINCH)
  488.     /*
  489.      * WINDOW CHANGE signal is handled with sig_winch().
  490.      */
  491.     signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
  492. #endif
  493.  
  494.     /*
  495.      * We want the STOP signal to work, to make mch_suspend() work
  496.      */
  497. #ifdef SIGTSTP
  498.     signal(SIGTSTP, SIG_DFL);
  499. #endif
  500.  
  501.     /*
  502.      * We want to ignore breaking of PIPEs.
  503.      */
  504. #ifdef SIGPIPE
  505.     signal(SIGPIPE, SIG_IGN);
  506. #endif
  507.  
  508.     /*
  509.      * Arrange for other signals to gracefully shutdown Vim.
  510.      */
  511.     catch_signals(deathtrap);
  512. }
  513.  
  514.     static void
  515. catch_signals(func)
  516.     RETSIGTYPE (*func)();
  517. {
  518.     int        i;
  519.  
  520.     for (i = 0; signal_info[i].dump != -1; i++)
  521.         signal(signal_info[i].sig, func);
  522. }
  523.  
  524.     void
  525. reset_signals()
  526. {
  527.     catch_signals(SIG_DFL);
  528. }
  529.  
  530. /*
  531.  * Check_win checks whether we have an interactive window.
  532.  */
  533.     int
  534. mch_check_win(argc, argv)
  535.     int        argc;
  536.     char    **argv;
  537. {
  538.     if (isatty(1))
  539.         return OK;
  540.     return FAIL;
  541. }
  542.  
  543.     int
  544. mch_check_input()
  545. {
  546.     if (isatty(0))
  547.         return OK;
  548.     return FAIL;
  549. }
  550.  
  551. #if defined(HAVE_X11) && defined(WANT_X11)
  552. /*
  553.  * X Error handler, otherwise X just exits!  (very rude) -- webb
  554.  */
  555.     static int
  556. x_error_handler(dpy, error_event)
  557.     Display        *dpy;
  558.     XErrorEvent    *error_event;
  559. {
  560.     XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
  561.     STRCAT(IObuff, "\nVim: Got X error\n");
  562.  
  563. #if 1
  564.     preserve_exit();                /* preserve files and exit */
  565. #else
  566.     printf(IObuff);                    /* print error message and continue */
  567.                                     /* Makes my system hang */
  568. #endif
  569.  
  570.     return 0;            /* NOTREACHED */
  571. }
  572.  
  573. /*
  574.  * Another X Error handler, just used to check for errors.
  575.  */
  576.     static int
  577. x_error_check(dpy, error_event)
  578.     Display    *dpy;
  579.     XErrorEvent    *error_event;
  580. {
  581.     got_x_error = TRUE;
  582.     return 0;
  583. }
  584.  
  585. /*
  586.  * try to get x11 window and display
  587.  *
  588.  * return FAIL for failure, OK otherwise
  589.  */
  590.     static int
  591. get_x11_windis()
  592. {
  593.     char            *winid;
  594.     XTextProperty    text_prop;
  595.     int                (*old_handler)();
  596.     static int        result = -1;
  597.     static int        x11_display_opened_here = FALSE;
  598.  
  599.     /* X just exits if it finds an error otherwise! */
  600.     XSetErrorHandler(x_error_handler);
  601.  
  602. #ifdef USE_GUI_X11
  603.     if (gui.in_use)
  604.     {
  605.         /*
  606.          * If the X11 display was opened here before, for the window where Vim
  607.          * was started, close that one now to avoid a memory leak.
  608.          */
  609.         if (x11_display_opened_here && x11_display != NULL)
  610.         {
  611.             XCloseDisplay(x11_display);
  612.             x11_display = NULL;
  613.             x11_display_opened_here = FALSE;
  614.         }
  615.         return gui_get_x11_windis(&x11_window, &x11_display);
  616.     }
  617. #endif
  618.  
  619.     if (result != -1)        /* Have already been here and set this */
  620.         return result;        /* Don't do all these X calls again */
  621.  
  622.     /*
  623.      * If WINDOWID not set, should try another method to find out
  624.      * what the current window number is. The only code I know for
  625.      * this is very complicated.
  626.      * We assume that zero is invalid for WINDOWID.
  627.      */
  628.     if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL) 
  629.         x11_window = (Window)atol(winid);
  630.     if (x11_window != 0 && x11_display == NULL)
  631.     {
  632. #ifdef SIGALRM
  633.         RETSIGTYPE (*sig_save)();
  634.  
  635.         /*
  636.          * Opening the Display may hang if the DISPLAY setting is wrong, or
  637.          * the network connection is bad.  Set an alarm timer to get out.
  638.          */
  639.         sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
  640.                                                  (RETSIGTYPE (*)())sig_alarm);
  641.         alarm(2);
  642. #endif
  643.         x11_display = XOpenDisplay(NULL);
  644. #ifdef SIGALRM
  645.         alarm(0);
  646.         signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
  647. #endif
  648.         if (x11_display != NULL)
  649.         {
  650.             /*
  651.              * Try to get the window title.  I don't actually want it yet, so
  652.              * there may be a simpler call to use, but this will cause the
  653.              * error handler x_error_check() to be called if anything is wrong,
  654.              * such as the window pointer being invalid (as can happen when the
  655.              * user changes his DISPLAY, but not his WINDOWID) -- webb
  656.              */
  657.             old_handler = XSetErrorHandler(x_error_check);
  658.             got_x_error = FALSE;
  659.             if (XGetWMName(x11_display, x11_window, &text_prop))
  660.                 XFree((void *)text_prop.value);
  661.             XSync(x11_display, False);
  662.             if (got_x_error)
  663.             {
  664.                 /* Maybe window id is bad */
  665.                 x11_window = 0;
  666.                 XCloseDisplay(x11_display);
  667.                 x11_display = NULL;
  668.             }
  669.             else
  670.                 x11_display_opened_here = TRUE;
  671.             XSetErrorHandler(old_handler);
  672.         }
  673.     }
  674.     if (x11_window == 0 || x11_display == NULL)
  675.         return (result = FAIL);
  676.     return (result = OK);
  677. }
  678.  
  679. /*
  680.  * Determine original x11 Window Title
  681.  */
  682.     static int
  683. get_x11_title(test_only)
  684.     int        test_only;
  685. {
  686.     XTextProperty    text_prop;
  687.     int                retval = FALSE;
  688.  
  689.     if (get_x11_windis() == OK)
  690.     {
  691.             /* Get window name if any */
  692.         if (XGetWMName(x11_display, x11_window, &text_prop))
  693.         {
  694.             if (text_prop.value != NULL)
  695.             {
  696.                 retval = TRUE;
  697.                 if (!test_only)
  698.                     oldtitle = strsave((char_u *)text_prop.value);
  699.             }
  700.             XFree((void *)text_prop.value);
  701.         }
  702.     }
  703.     if (oldtitle == NULL && !test_only)        /* could not get old title */
  704.         oldtitle = fixedtitle;
  705.  
  706.     return retval;
  707. }
  708.  
  709. /*
  710.  * Determine original x11 Window icon
  711.  */
  712.  
  713.     static int
  714. get_x11_icon(test_only)
  715.     int        test_only;
  716. {
  717.     XTextProperty    text_prop;
  718.     int                retval = FALSE;
  719.  
  720.     if (get_x11_windis() == OK)
  721.     {
  722.             /* Get icon name if any */
  723.         if (XGetWMIconName(x11_display, x11_window, &text_prop))
  724.         {
  725.             if (text_prop.value != NULL)
  726.             {
  727.                 retval = TRUE;
  728.                 if (!test_only)
  729.                     oldicon = strsave((char_u *)text_prop.value);
  730.             }
  731.             XFree((void *)text_prop.value);
  732.         }
  733.     }
  734.  
  735.         /* could not get old icon, use terminal name */
  736.     if (oldicon == NULL && !test_only)
  737.     {
  738.         if (STRNCMP(term_strings[KS_NAME], "builtin_", 8) == 0)
  739.             oldicon = term_strings[KS_NAME] + 8;
  740.         else
  741.             oldicon = term_strings[KS_NAME];
  742.     }
  743.  
  744.     return retval;
  745. }
  746.  
  747. /*
  748.  * Set x11 Window Title
  749.  *
  750.  * get_x11_windis() must be called before this and have returned OK
  751.  */
  752.     static void
  753. set_x11_title(title)
  754.     char_u      *title;
  755. {
  756. #if XtSpecificationRelease >= 4
  757.     XTextProperty text_prop;
  758.  
  759.     text_prop.value = title;
  760.     text_prop.nitems = STRLEN(title);
  761.     text_prop.encoding = XA_STRING;
  762.     text_prop.format = 8;
  763.     XSetWMName(x11_display, x11_window, &text_prop);
  764. #else
  765.     XStoreName(x11_display, x11_window, (char *)title);
  766. #endif
  767.     XFlush(x11_display);
  768. }
  769.  
  770. /*
  771.  * Set x11 Window icon
  772.  *
  773.  * get_x11_windis() must be called before this and have returned OK
  774.  */
  775.     static void
  776. set_x11_icon(icon)
  777.     char_u      *icon;
  778. {
  779. #if XtSpecificationRelease >= 4
  780.     XTextProperty text_prop;
  781.  
  782.     text_prop.value = icon;
  783.     text_prop.nitems = STRLEN(icon);
  784.     text_prop.encoding = XA_STRING;
  785.     text_prop.format = 8;
  786.     XSetWMIconName(x11_display, x11_window, &text_prop);
  787. #else
  788.     XSetIconName(x11_display, x11_window, (char *)icon);
  789. #endif
  790.     XFlush(x11_display);
  791. }
  792.  
  793. #else    /* HAVE_X11 && WANT_X11 */
  794.  
  795.     static int
  796. get_x11_title(test_only)
  797.     int        test_only;
  798. {
  799.     if (!test_only)
  800.         oldtitle = fixedtitle;
  801.     return FALSE;
  802. }
  803.  
  804.     static int
  805. get_x11_icon(test_only)
  806.     int        test_only;
  807. {
  808.     if (!test_only)
  809.     {
  810.         if (STRNCMP(term_strings[KS_NAME], "builtin_", 8) == 0)
  811.             oldicon = term_strings[KS_NAME] + 8;
  812.         else
  813.             oldicon = term_strings[KS_NAME];
  814.     }
  815.     return FALSE;
  816. }
  817.  
  818. #endif    /* HAVE_X11 && WANT_X11 */
  819.  
  820.     int
  821. mch_can_restore_title()
  822. {
  823. #ifdef USE_GUI
  824.     /*
  825.      * If GUI is (going to be) used, we can always set the window title.
  826.      * Saves a bit of time, because the X11 display server does not need to be
  827.      * contacted.
  828.      */
  829.     if (gui.starting || gui.in_use)
  830.         return TRUE;
  831. #endif
  832.     return get_x11_title(TRUE);
  833. }
  834.  
  835.     int
  836. mch_can_restore_icon()
  837. {
  838. #ifdef USE_GUI
  839.     /*
  840.      * If GUI is (going to be) used, we can always set the icon name.
  841.      * Saves a bit of time, because the X11 display server does not need to be
  842.      * contacted.
  843.      */
  844.     if (gui.starting || gui.in_use)
  845.         return TRUE;
  846. #endif
  847.     return get_x11_icon(TRUE);
  848. }
  849.  
  850. /*
  851.  * Set the window title and icon.
  852.  * Currently only works for x11.
  853.  */
  854.     void
  855. mch_settitle(title, icon)
  856.     char_u *title;
  857.     char_u *icon;
  858. {
  859.     int            type = 0;
  860.  
  861.     if (term_strings[KS_NAME] == NULL)        /* no terminal name (yet) */
  862.         return;
  863.     if (title == NULL && icon == NULL)        /* nothing to do */
  864.         return;
  865.  
  866. /*
  867.  * if the window ID and the display is known, we may use X11 calls
  868.  */
  869. #if defined(HAVE_X11) && defined(WANT_X11)
  870.     if (get_x11_windis() == OK)
  871.         type = 1;
  872. #endif
  873.  
  874.     /*
  875.      * Note: if terminal is xterm, title is set with escape sequence rather
  876.      *          than x11 calls, because the x11 calls don't always work
  877.      * Check only if the start of the terminal name is "xterm", also catch
  878.      * "xterms".
  879.      */
  880.     if (is_xterm(term_strings[KS_NAME]))
  881.         type = 2;
  882.  
  883.     if (is_iris_ansi(term_strings[KS_NAME]))
  884.         type = 3;
  885.  
  886.     if (type)
  887.     {
  888.         if (title != NULL)
  889.         {
  890.             if (oldtitle == NULL)                /* first call, save title */
  891.                 (void)get_x11_title(FALSE);
  892.  
  893.             switch(type)
  894.             {
  895. #if defined(HAVE_X11) && defined(WANT_X11)
  896.             case 1:    set_x11_title(title);                /* x11 */
  897.                     break;
  898. #endif
  899.             case 2: outstrn((char_u *)"\033]2;");        /* xterm */
  900.                     outstrn(title);
  901.                     outchar(Ctrl('G'));
  902.                     flushbuf();
  903.                     break;
  904.  
  905.             case 3: outstrn((char_u *)"\033P1.y");        /* iris-ansi */
  906.                     outstrn(title);
  907.                     outstrn((char_u *)"\234");
  908.                     flushbuf();
  909.                     break;
  910.             }
  911.         }
  912.  
  913.         if (icon != NULL)
  914.         {
  915.             if (oldicon == NULL)                /* first call, save icon */
  916.                 get_x11_icon(FALSE);
  917.  
  918.             switch(type)
  919.             {
  920. #if defined(HAVE_X11) && defined(WANT_X11)
  921.             case 1:    set_x11_icon(icon);                    /* x11 */
  922.                     break;
  923. #endif
  924.             case 2: outstrn((char_u *)"\033]1;");        /* xterm */
  925.                     outstrn(icon);
  926.                     outchar(Ctrl('G'));
  927.                     flushbuf();
  928.                     break;
  929.  
  930.             case 3: outstrn((char_u *)"\033P3.y");        /* iris-ansi */
  931.                     outstrn(icon);
  932.                     outstrn((char_u *)"\234");
  933.                     flushbuf();
  934.                     break;
  935.             }
  936.         }
  937.     }
  938. }
  939.  
  940.     int
  941. is_xterm(name)
  942.     char_u *name;
  943. {
  944.     if (name == NULL)
  945.         return FALSE;
  946.     return (vim_strnicmp(name, (char_u *)"xterm", (size_t)5) == 0 ||
  947.                         STRCMP(name, "builtin_xterm") == 0);
  948. }
  949.  
  950.     int
  951. is_iris_ansi(name)
  952.     char_u    *name;
  953. {
  954.     if (name == NULL)
  955.         return FALSE;
  956.     return (vim_strnicmp(name, (char_u *)"iris-ansi", (size_t)9) == 0 ||
  957.                         STRCMP(name, "builtin_iris-ansi") == 0);
  958. }
  959.  
  960. /*
  961.  * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
  962.  * This should include all windowed terminal emulators.
  963.  */
  964.     int
  965. is_fastterm(name)
  966.     char_u    *name;
  967. {
  968.     if (name == NULL)
  969.         return FALSE;
  970.     if (is_xterm(name) || is_iris_ansi(name))
  971.         return TRUE;
  972.     return (vim_strnicmp(name, (char_u *)"hpterm", (size_t)6) == 0 ||
  973.             vim_strnicmp(name, (char_u *)"sun-cmd", (size_t)7) == 0 ||
  974.             vim_strnicmp(name, (char_u *)"screen", (size_t)6) == 0 ||
  975.             vim_strnicmp(name, (char_u *)"dtterm", (size_t)6) == 0);
  976. }
  977.  
  978. /*
  979.  * Restore the window/icon title.
  980.  * which is one of:
  981.  *    1  Just restore title
  982.  *  2  Just restore icon
  983.  *    3  Restore title and icon
  984.  */
  985.     void
  986. mch_restore_title(which)
  987.     int which;
  988. {
  989.     mch_settitle((which & 1) ? oldtitle : NULL, (which & 2) ? oldicon : NULL);
  990. }
  991.  
  992. /*
  993.  * Insert user name in s[len].
  994.  * Return OK if a name found.
  995.  */
  996.     int
  997. mch_get_user_name(s, len)
  998.     char_u    *s;
  999.     int        len;
  1000. {
  1001. #if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
  1002.     struct passwd    *pw;
  1003. #endif
  1004.     uid_t            uid;
  1005.  
  1006.     uid = getuid();
  1007. #if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
  1008.     if ((pw = getpwuid(uid)) != NULL &&
  1009.                                    pw->pw_name != NULL && *pw->pw_name != NUL)
  1010.     {
  1011.         STRNCPY(s, pw->pw_name, len);
  1012.         return OK;
  1013.     }
  1014. #endif
  1015.     sprintf((char *)s, "%d", (int)uid);        /* assumes s is long enough */
  1016.     return FAIL;                            /* a number is not a name */
  1017. }
  1018.  
  1019. /*
  1020.  * Insert host name is s[len].
  1021.  */
  1022.  
  1023. #ifdef HAVE_SYS_UTSNAME_H
  1024.     void
  1025. mch_get_host_name(s, len)
  1026.     char_u    *s;
  1027.     int        len;
  1028. {
  1029.     struct utsname vutsname;
  1030.  
  1031.     uname(&vutsname);
  1032.     STRNCPY(s, vutsname.nodename, len);
  1033. }
  1034. #else /* HAVE_SYS_UTSNAME_H */
  1035.  
  1036. # ifdef HAVE_SYS_SYSTEMINFO_H
  1037. #  define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
  1038. # endif
  1039.  
  1040.     void
  1041. mch_get_host_name(s, len)
  1042.     char_u    *s;
  1043.     int        len;
  1044. {
  1045.     gethostname((char *)s, len);
  1046. }
  1047. #endif /* HAVE_SYS_UTSNAME_H */
  1048.  
  1049. /*
  1050.  * return process ID
  1051.  */
  1052.     long
  1053. mch_get_pid()
  1054. {
  1055.     return (long)getpid();
  1056. }
  1057.  
  1058. #if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
  1059. static char *strerror __ARGS((int));
  1060.  
  1061.     static char *
  1062. strerror(err)
  1063.     int err;
  1064. {
  1065.     extern int        sys_nerr;
  1066.     extern char        *sys_errlist[];
  1067.     static char        er[20];
  1068.  
  1069.     if (err > 0 && err < sys_nerr)
  1070.         return (sys_errlist[err]);
  1071.     sprintf(er, "Error %d", err);
  1072.     return er;
  1073. }
  1074. #endif
  1075.  
  1076. /*
  1077.  * Get name of current directory into buffer 'buf' of length 'len' bytes.
  1078.  * Return OK for success, FAIL for failure.
  1079.  */
  1080.     int 
  1081. mch_dirname(buf, len)
  1082.     char_u    *buf;
  1083.     int        len;
  1084. {
  1085. #if defined(USE_GETCWD)
  1086.     if (getcwd((char *)buf, len) == NULL)
  1087.     {
  1088.         STRCPY(buf, strerror(errno));
  1089.         return FAIL;
  1090.     }
  1091.     return OK;
  1092. #else
  1093.     return (getwd((char *)buf) != NULL ? OK : FAIL);
  1094. #endif
  1095. }
  1096.  
  1097. #ifdef __EMX__
  1098. /*
  1099.  * Replace all slashes by backslashes.
  1100.  */
  1101.     static void
  1102. slash_adjust(p)
  1103.     char_u    *p;
  1104. {
  1105.     while (*p)
  1106.     {
  1107.         if (*p == '/')
  1108.             *p = '\\';
  1109.         ++p;
  1110.     }
  1111. }
  1112. #endif
  1113.  
  1114. /*
  1115.  * Get absolute filename into buffer 'buf' of length 'len' bytes.
  1116.  *
  1117.  * return FAIL for failure, OK for success
  1118.  */
  1119.     int 
  1120. FullName(fname, buf, len, force)
  1121.     char_u *fname, *buf;
  1122.     int len;
  1123.     int    force;            /* also expand when already absolute path name */
  1124. {
  1125.     int        l;
  1126. #ifdef OS2
  1127.     int        only_drive;    /* only a drive letter is specified in file name */
  1128. #endif
  1129. #ifdef HAVE_FCHDIR
  1130.     int        fd = -1;
  1131.     static int    dont_fchdir = FALSE;    /* TRUE when fchdir() doesn't work */
  1132. #endif
  1133.     char_u    olddir[MAXPATHL];
  1134.     char_u    *p;
  1135.     char_u    c;
  1136.     int        retval = OK;
  1137.  
  1138.     if (fname == NULL)    /* always fail */
  1139.     {
  1140.         *buf = NUL;
  1141.         return FAIL;
  1142.     }
  1143.  
  1144.     *buf = 0;
  1145.     if (force || !isFullName(fname))    /* if forced or not an absolute path */
  1146.     {
  1147.         /*
  1148.          * If the file name has a path, change to that directory for a moment,
  1149.          * and then do the getwd() (and get back to where we were).
  1150.          * This will get the correct path name with "../" things.
  1151.          */
  1152. #ifdef OS2
  1153.         only_drive = 0;
  1154.         if (((p = vim_strrchr(fname, '/')) != NULL) ||
  1155.             ((p = vim_strrchr(fname, '\\')) != NULL) ||
  1156.             (((p = vim_strchr(fname,  ':')) != NULL) && ++only_drive))
  1157. #else
  1158.         if ((p = vim_strrchr(fname, '/')) != NULL)
  1159. #endif
  1160.         {
  1161. #ifdef HAVE_FCHDIR
  1162.             /*
  1163.              * Use fchdir() if possible, it's said to be faster and more
  1164.              * reliable.  But on SunOS 4 it might not work.  Check this by
  1165.              * doing a fchdir() right now.
  1166.              */
  1167.             if (!dont_fchdir)
  1168.             {
  1169.                 fd = open(".", O_RDONLY | O_EXTRA);
  1170.                 if (fd >= 0 && fchdir(fd) < 0)
  1171.                 {
  1172.                     close(fd);
  1173.                     fd = -1;
  1174.                     dont_fchdir = TRUE;        /* don't try again */
  1175.                 }
  1176.             }
  1177. #endif
  1178.             if (
  1179. #ifdef HAVE_FCHDIR
  1180.                 fd < 0 &&
  1181. #endif
  1182.                             mch_dirname(olddir, MAXPATHL) == FAIL)
  1183.             {
  1184.                 p = NULL;        /* can't get current dir: don't chdir */
  1185.                 retval = FAIL;
  1186.             }
  1187.             else
  1188.             {
  1189. #ifdef OS2
  1190.                 /*
  1191.                  * compensate for case where ':' from "D:" was the only
  1192.                  * path separator detected in the file name; the _next_
  1193.                  * character has to be removed, and then restored later.
  1194.                  */
  1195.                 if (only_drive)
  1196.                     p++;
  1197. #endif
  1198.                 c = *p;
  1199.                 *p = NUL;
  1200.                 if (vim_chdir((char *)fname))
  1201.                     retval = FAIL;
  1202.                 else
  1203.                     fname = p + 1;
  1204.                 *p = c;
  1205. #ifdef OS2
  1206.                 if (only_drive)
  1207.                 {
  1208.                     p--;
  1209.                     if (retval != FAIL)
  1210.                         fname--;
  1211.                 }
  1212. #endif
  1213.             }
  1214.         }
  1215.         if (mch_dirname(buf, len) == FAIL)
  1216.         {
  1217.             retval = FAIL;
  1218.             *buf = NUL;
  1219.         }
  1220.         l = STRLEN(buf);
  1221.         if (l && buf[l - 1] != '/')
  1222.             STRCAT(buf, "/");
  1223.         if (p != NULL)
  1224.         {
  1225. #ifdef HAVE_FCHDIR
  1226.             if (fd >= 0)
  1227.             {
  1228.                 fchdir(fd);
  1229.                 close(fd);
  1230.             }
  1231.             else
  1232. #endif
  1233.                 vim_chdir((char *)olddir);
  1234.         }
  1235.     }
  1236.     STRCAT(buf, fname);
  1237. #ifdef OS2
  1238.     slash_adjust(buf);
  1239. #endif
  1240.     return retval;
  1241. }
  1242.  
  1243. /*
  1244.  * return TRUE is fname is an absolute path name
  1245.  */
  1246.     int
  1247. isFullName(fname)
  1248.     char_u        *fname;
  1249. {
  1250. #ifdef __EMX__
  1251.     return _fnisabs(fname);
  1252. #else
  1253.     return (*fname == '/' || *fname == '~');
  1254. #endif
  1255. }
  1256.  
  1257. /*
  1258.  * get file permissions for 'name'
  1259.  */
  1260.     long 
  1261. getperm(name)
  1262.     char_u *name;
  1263. {
  1264.     struct stat statb;
  1265.  
  1266.     if (stat((char *)name, &statb))
  1267.         return -1;
  1268.     return statb.st_mode;
  1269. }
  1270.  
  1271. /*
  1272.  * set file permission for 'name' to 'perm'
  1273.  *
  1274.  * return FAIL for failure, OK otherwise
  1275.  */
  1276.     int
  1277. setperm(name, perm)
  1278.     char_u *name;
  1279.     int perm;
  1280. {
  1281.     return (chmod((char *)name, (mode_t)perm) == 0 ? OK : FAIL);
  1282. }
  1283.  
  1284. /*
  1285.  * return TRUE if "name" is a directory
  1286.  * return FALSE if "name" is not a directory
  1287.  * return FALSE for error
  1288.  */
  1289.     int 
  1290. mch_isdir(name)
  1291.     char_u *name;
  1292. {
  1293.     struct stat statb;
  1294.  
  1295.     if (stat((char *)name, &statb))
  1296.         return FALSE;
  1297. #ifdef _POSIX_SOURCE
  1298.     return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
  1299. #else
  1300.     return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
  1301. #endif
  1302. }
  1303.  
  1304.     void
  1305. mch_windexit(r)
  1306.     int r;
  1307. {
  1308.     settmode(0);
  1309.     exiting = TRUE;
  1310.     mch_settitle(oldtitle, oldicon);    /* restore xterm title */
  1311.     stoptermcap();
  1312.     flushbuf();
  1313.     ml_close_all(TRUE);                 /* remove all memfiles */
  1314.     may_core_dump();
  1315.     exit(r);
  1316. }
  1317.  
  1318.     static void
  1319. may_core_dump()
  1320. {
  1321. #ifdef SIGQUIT
  1322.     signal(SIGQUIT, SIG_DFL);
  1323.     if (core_dump)
  1324.         kill(getpid(), SIGQUIT);        /* force a core dump */
  1325. #endif
  1326. }
  1327.  
  1328. static int curr_tmode = 0;    /* contains current raw/cooked mode (0 = cooked) */
  1329.  
  1330.     void
  1331. mch_settmode(raw)
  1332.     int                raw;
  1333. {
  1334.     static int first = TRUE;
  1335.  
  1336.     /* Why is NeXT excluded here (and not in unixunix.h)? */
  1337. #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
  1338.     /* for "new" tty systems */
  1339. # ifdef HAVE_TERMIOS_H
  1340.     static struct termios told;
  1341.            struct termios tnew;
  1342. # else
  1343.     static struct termio told;
  1344.            struct termio tnew;
  1345. # endif
  1346.  
  1347. # ifdef TIOCLGET
  1348.     static unsigned long tty_local;
  1349. # endif
  1350.  
  1351.     if (raw)
  1352.     {
  1353.         if (first)
  1354.         {
  1355.             first = FALSE;
  1356. # ifdef TIOCLGET
  1357.             ioctl(0, TIOCLGET, &tty_local);
  1358. # endif
  1359. # if defined(HAVE_TERMIOS_H)
  1360.             tcgetattr(0, &told);
  1361. # else
  1362.             ioctl(0, TCGETA, &told);
  1363. # endif
  1364.         }
  1365.         tnew = told;
  1366.         /*
  1367.          * ICRNL enables typing ^V^M
  1368.          */
  1369.         tnew.c_iflag &= ~ICRNL;
  1370.         tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
  1371. # if defined(IEXTEN) && !defined(MINT)
  1372.                     | IEXTEN        /* IEXTEN enables typing ^V on SOLARIS */
  1373.                                     /* but it breaks function keys on MINT */
  1374. # endif
  1375.                                 );
  1376.         tnew.c_cc[VMIN] = 1;            /* return after 1 char */
  1377.         tnew.c_cc[VTIME] = 0;            /* don't wait */
  1378. # if defined(HAVE_TERMIOS_H)
  1379.         tcsetattr(0, TCSANOW, &tnew);
  1380. # else
  1381.         ioctl(0, TCSETA, &tnew);
  1382. # endif
  1383.     }
  1384.     else
  1385.     {
  1386. # if defined(HAVE_TERMIOS_H)
  1387.         tcsetattr(0, TCSANOW, &told);
  1388. # else
  1389.         ioctl(0, TCSETA, &told);
  1390. # endif
  1391. # ifdef TIOCLGET
  1392.         ioctl(0, TIOCLSET, &tty_local);
  1393. # endif
  1394.     }
  1395. #else
  1396. # ifndef TIOCSETN
  1397. #  define TIOCSETN TIOCSETP        /* for hpux 9.0 */
  1398. # endif
  1399.     /* for "old" tty systems */
  1400.     static struct sgttyb ttybold;
  1401.            struct sgttyb ttybnew;
  1402.  
  1403.     if (raw)
  1404.     {
  1405.         if (first)
  1406.         {
  1407.             first = FALSE;
  1408.             ioctl(0, TIOCGETP, &ttybold);
  1409.         }
  1410.         ttybnew = ttybold;
  1411.         ttybnew.sg_flags &= ~(CRMOD | ECHO);
  1412.         ttybnew.sg_flags |= RAW;
  1413.         ioctl(0, TIOCSETN, &ttybnew);
  1414.     }
  1415.     else
  1416.         ioctl(0, TIOCSETN, &ttybold);
  1417. #endif
  1418.     curr_tmode = raw;
  1419. }
  1420.  
  1421. /*
  1422.  * Try to get the code for "t_kb" from the stty setting
  1423.  *
  1424.  * Even if termcap claims a backspace key, the user's setting *should*
  1425.  * prevail.  stty knows more about reality than termcap does, and if
  1426.  * somebody's usual erase key is DEL (which, for most BSD users, it will
  1427.  * be), they're going to get really annoyed if their erase key starts
  1428.  * doing forward deletes for no reason. (Eric Fischer)
  1429.  */
  1430.     void
  1431. get_stty()
  1432. {
  1433.     char_u    buf[2];
  1434.     char_u    *p;
  1435.  
  1436.     /* Why is NeXT excluded here (and not in unixunix.h)? */
  1437. #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
  1438.     /* for "new" tty systems */
  1439. # ifdef HAVE_TERMIOS_H
  1440.     struct termios keys;
  1441. # else
  1442.     struct termio keys;
  1443. # endif
  1444.  
  1445. # if defined(HAVE_TERMIOS_H)
  1446.     if (tcgetattr(0, &keys) != -1)
  1447. # else
  1448.     if (ioctl(0, TCGETA, &keys) != -1)
  1449. # endif
  1450.     {
  1451.         buf[0] = keys.c_cc[VERASE];
  1452. #else
  1453.     /* for "old" tty systems */
  1454.     struct sgttyb keys;
  1455.  
  1456.     if (ioctl(0, TIOCGETP, &keys) != -1)
  1457.     {
  1458.         buf[0] = keys.sg_erase;
  1459. #endif
  1460.         buf[1] = NUL;
  1461.         add_termcode((char_u *)"kb", buf);
  1462.  
  1463.         /*
  1464.          * If <BS> and <DEL> are now the same, redefine <DEL>.
  1465.          */
  1466.         p = find_termcode((char_u *)"kD");
  1467.         if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
  1468.             do_fixdel();
  1469.     }
  1470. #if 0
  1471.     }        /* to keep cindent happy */
  1472. #endif
  1473. }
  1474.  
  1475. #ifdef USE_MOUSE
  1476. /*
  1477.  * set mouse clicks on or off (only works for xterms)
  1478.  */
  1479.     void
  1480. mch_setmouse(on)
  1481.     int        on;
  1482. {
  1483.     static int    ison = FALSE;
  1484.  
  1485.     if (on == ison)        /* return quickly if nothing to do */
  1486.         return;
  1487.  
  1488.     if (is_xterm(term_strings[KS_NAME]))
  1489.     {
  1490.         if (on)
  1491.             outstrn((char_u *)"\033[?1000h"); /* xterm: enable mouse events */
  1492.         else
  1493.             outstrn((char_u *)"\033[?1000l"); /* xterm: disable mouse events */
  1494.     }
  1495.     ison = on;
  1496. }
  1497. #endif
  1498.  
  1499. /*
  1500.  * set screen mode, always fails.
  1501.  */
  1502.     int
  1503. mch_screenmode(arg)
  1504.     char_u     *arg;
  1505. {
  1506.     EMSG("Screen mode setting not supported");
  1507.     return FAIL;
  1508. }
  1509.  
  1510. /*
  1511.  * Try to get the current window size:
  1512.  * 1. with an ioctl(), most accurate method
  1513.  * 2. from the environment variables LINES and COLUMNS
  1514.  * 3. from the termcap
  1515.  * 4. keep using the old values
  1516.  */
  1517.     int
  1518. mch_get_winsize()
  1519. {
  1520.     int            old_Rows = Rows;
  1521.     int            old_Columns = Columns;
  1522.     char_u        *p;
  1523.  
  1524. #ifdef USE_GUI
  1525.     if (gui.in_use)
  1526.         return gui_mch_get_winsize();
  1527. #endif
  1528.  
  1529.     Columns = 0;
  1530.     Rows = 0;
  1531.  
  1532. /*
  1533.  * For OS/2 use _scrsize().
  1534.  */
  1535. # ifdef __EMX__
  1536.     {
  1537.         int s[2];
  1538.         _scrsize(s);
  1539.         Columns = s[0];
  1540.         Rows = s[1];
  1541.     }
  1542. # endif
  1543.  
  1544. /*
  1545.  * 1. try using an ioctl. It is the most accurate method.
  1546.  *
  1547.  * Try using TIOCGWINSZ first, some systems that have it also define TIOCGSIZE
  1548.  * but don't have a struct ttysize.
  1549.  */
  1550. # ifdef TIOCGWINSZ
  1551.     {
  1552.         struct winsize    ws;
  1553.  
  1554.         if (ioctl(0, TIOCGWINSZ, &ws) == 0)
  1555.         {
  1556.             Columns = ws.ws_col;
  1557.             Rows = ws.ws_row;
  1558.         }
  1559.     }
  1560. # else /* TIOCGWINSZ */
  1561. #  ifdef TIOCGSIZE
  1562.     {
  1563.         struct ttysize    ts;
  1564.  
  1565.         if (ioctl(0, TIOCGSIZE, &ts) == 0)
  1566.         {
  1567.             Columns = ts.ts_cols;
  1568.             Rows = ts.ts_lines;
  1569.         }
  1570.     }
  1571. #  endif /* TIOCGSIZE */
  1572. # endif /* TIOCGWINSZ */
  1573.  
  1574. /*
  1575.  * 2. get size from environment
  1576.  */
  1577.     if (Columns == 0 || Rows == 0)
  1578.     {
  1579.         if ((p = (char_u *)getenv("LINES")))
  1580.             Rows = atoi((char *)p);
  1581.         if ((p = (char_u *)getenv("COLUMNS")))
  1582.             Columns = atoi((char *)p);
  1583.     }
  1584.  
  1585. #ifdef HAVE_TGETENT
  1586. /*
  1587.  * 3. try reading the termcap
  1588.  */
  1589.     if (Columns == 0 || Rows == 0)
  1590.         getlinecol();    /* get "co" and "li" entries from termcap */
  1591. #endif
  1592.  
  1593. /*
  1594.  * 4. If everything fails, use the old values
  1595.  */
  1596.     if (Columns <= 0 || Rows <= 0)
  1597.     {
  1598.         Columns = old_Columns;
  1599.         Rows = old_Rows;
  1600.         return FAIL;
  1601.     }
  1602.  
  1603.     check_winsize();
  1604.  
  1605. /* if size changed: screenalloc will allocate new screen buffers */
  1606.     return OK;
  1607. }
  1608.  
  1609.     void
  1610. mch_set_winsize()
  1611. {
  1612.     char_u    string[10];
  1613.  
  1614. #ifdef USE_GUI
  1615.     if (gui.in_use)
  1616.     {
  1617.         gui_mch_set_winsize();
  1618.         return;
  1619.     }
  1620. #endif
  1621.  
  1622.     /* try to set the window size to Rows and Columns */
  1623.     if (is_iris_ansi(term_strings[KS_NAME]))
  1624.     {
  1625.         sprintf((char *)string, "\033[203;%ld;%ld/y", Rows, Columns);
  1626.         outstrn(string);
  1627.         flushbuf();
  1628.         screen_start();                    /* don't know where cursor is now */
  1629.     }
  1630. }
  1631.  
  1632.     int 
  1633. call_shell(cmd, options)
  1634.     char_u    *cmd;
  1635.     int        options;        /* SHELL_FILTER if called by do_filter() */
  1636.                             /* SHELL_COOKED if term needs cooked mode */
  1637.                             /* SHELL_EXPAND if called by ExpandWildCards() */
  1638. {
  1639. #ifdef USE_SYSTEM        /* use system() to start the shell: simple but slow */
  1640.  
  1641.     int        x;
  1642. #ifndef __EMX__
  1643.     char_u    newcmd[1024];    /* only needed for unix */
  1644. #else /* __EMX__ */
  1645.     /*
  1646.      * Set the preferred shell in the EMXSHELL environment variable (but
  1647.      * only if it is different from what is already in the environment).
  1648.      * Emx then takes care of whether to use "/c" or "-c" in an
  1649.      * intelligent way. Simply pass the whole thing to emx's system() call.
  1650.      * Emx also starts an interactive shell if system() is passed an empty
  1651.      * string.
  1652.      */
  1653.     char_u *p, *old;
  1654.  
  1655.     if (((old = getenv("EMXSHELL")) == NULL) || strcmp(old, p_sh))
  1656.     {
  1657.         /* should check HAVE_SETENV, but I know we don't have it. */
  1658.         p = alloc(10 + strlen(p_sh));
  1659.         if (p)
  1660.         {
  1661.             sprintf(p, "EMXSHELL=%s", p_sh);
  1662.             putenv(p);    /* don't free the pointer! */
  1663.         }
  1664.     }
  1665. #endif
  1666.  
  1667.     flushbuf();
  1668.  
  1669.     if (options & SHELL_COOKED)
  1670.         settmode(0);                 /* set to cooked mode */
  1671.  
  1672. #ifdef __EMX__
  1673.     if (cmd == NULL)
  1674.         x = system("");    /* this starts an interactive shell in emx */
  1675.     else
  1676.         x = system(cmd);
  1677.     if (x == -1) /* system() returns -1 when error occurs in starting shell */
  1678.     {
  1679.         MSG_OUTSTR("\nCannot execute shell ");
  1680.         msg_outstr(p_sh);
  1681.         msg_outchar('\n');
  1682.     }
  1683. #else /* not __EMX__ */
  1684.     if (cmd == NULL)
  1685.         x = system(p_sh);
  1686.     else
  1687.     {
  1688.         sprintf(newcmd, "%s %s -c \"%s\"", p_sh,
  1689.                     extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
  1690.                     (char *)cmd);
  1691.         x = system(newcmd);
  1692.     }
  1693.     if (x == 127)
  1694.     {
  1695.          MSG_OUTSTR("\nCannot execute shell sh\n");
  1696.     }
  1697. #endif    /* __EMX__ */
  1698.     else if (x && !expand_interactively)
  1699.     {
  1700.         msg_outchar('\n');
  1701.         msg_outnum((long)x);
  1702.         MSG_OUTSTR(" returned\n");
  1703.     }
  1704.  
  1705.     settmode(1);                         /* set to raw mode */
  1706. #ifdef OS2
  1707.     /* external command may change the window size in OS/2, so check it */
  1708.     mch_get_winsize();
  1709. #endif
  1710.     resettitle();
  1711.     return (x ? FAIL : OK);
  1712.  
  1713. #else /* USE_SYSTEM */        /* don't use system(), use fork()/exec() */
  1714.  
  1715. #define EXEC_FAILED 122        /* Exit code when shell didn't execute.  Don't use
  1716.                                127, some shell use that already */
  1717.  
  1718.     char_u    newcmd[1024];
  1719.     int        pid;
  1720. #ifdef HAVE_UNION_WAIT
  1721.     union wait status;
  1722. #else
  1723.     int        status = -1;
  1724. #endif
  1725.     int        retval = FAIL;
  1726.     char    **argv = NULL;
  1727.     int        argc;
  1728.     int        i;
  1729.     char_u    *p;
  1730.     int        inquote;
  1731. #ifdef USE_GUI
  1732.     int        pty_master_fd = -1;        /* for pty's */
  1733.     int        pty_slave_fd = -1;
  1734.     char    *tty_name;
  1735.     int        fd_toshell[2];            /* for pipes */
  1736.     int        fd_fromshell[2];
  1737.     int        pipe_error = FALSE;
  1738. # ifdef HAVE_SETENV
  1739.     char    envbuf[50];
  1740. # else
  1741.     static char    envbuf_Rows[20];
  1742.     static char    envbuf_Columns[20];
  1743. # endif
  1744. #endif
  1745.     int        did_settmode = FALSE;    /* TRUE when settmode(1) called */
  1746.  
  1747.     flushbuf();
  1748.     if (options & SHELL_COOKED)
  1749.         settmode(0);            /* set to cooked mode */
  1750.  
  1751.     /*
  1752.      * 1: find number of arguments
  1753.      * 2: separate them and built argv[]
  1754.      */
  1755.     STRCPY(newcmd, p_sh);
  1756.     for (i = 0; i < 2; ++i)    
  1757.     {
  1758.         p = newcmd;
  1759.         inquote = FALSE;
  1760.         argc = 0;
  1761.         for (;;)
  1762.         {
  1763.             if (i == 1)
  1764.                 argv[argc] = (char *)p;
  1765.             ++argc;
  1766.             while (*p && (inquote || (*p != ' ' && *p != TAB)))
  1767.             {
  1768.                 if (*p == '"')
  1769.                     inquote = !inquote;
  1770.                 ++p;
  1771.             }
  1772.             if (*p == NUL)
  1773.                 break;
  1774.             if (i == 1)
  1775.                 *p++ = NUL;
  1776.             p = skipwhite(p);
  1777.         }
  1778.         if (i == 0)
  1779.         {
  1780.             argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
  1781.             if (argv == NULL)        /* out of memory */
  1782.                 goto error;
  1783.         }
  1784.     }
  1785.     if (cmd != NULL)
  1786.     {
  1787.         if (extra_shell_arg != NULL)
  1788.             argv[argc++] = (char *)extra_shell_arg;
  1789.         argv[argc++] = "-c";
  1790.         argv[argc++] = (char *)cmd;
  1791.     }
  1792.     argv[argc] = NULL;
  1793.  
  1794. #ifdef tower32
  1795.     /*
  1796.      * reap lost children (seems necessary on NCR Tower,
  1797.      * although I don't have a clue why...) (Slootman)
  1798.      */
  1799.     while (wait(&status) != 0 && errno != ECHILD)
  1800.         ;    /* do it again, if necessary */
  1801. #endif
  1802.  
  1803. #ifdef USE_GUI
  1804. /*
  1805.  * First try at using a pseudo-tty to get the stdin/stdout of the executed
  1806.  * command into the current window for the GUI.
  1807.  */
  1808.  
  1809.     if (gui.in_use && show_shell_mess)
  1810.     {
  1811.         /*
  1812.          * Try to open a master pty.
  1813.          * If this works, open the slave pty.
  1814.          * If the slave can't be opened, close the master pty.
  1815.          */
  1816.         if (p_guipty)
  1817.         {
  1818.             pty_master_fd = OpenPTY(&tty_name);        /* open pty */
  1819.             if (pty_master_fd >= 0 && ((pty_slave_fd =
  1820.                                        open(tty_name, O_RDWR | O_EXTRA)) < 0))
  1821.             {
  1822.                 close(pty_master_fd);
  1823.                 pty_master_fd = -1;
  1824.             }
  1825.         }
  1826.         /*
  1827.          * If opening a pty didn't work, try using pipes.
  1828.          */
  1829.         if (pty_master_fd < 0)
  1830.         {
  1831.             pipe_error = (pipe(fd_toshell) < 0);
  1832.             if (!pipe_error)                        /* pipe create OK */
  1833.             {
  1834.                 pipe_error = (pipe(fd_fromshell) < 0);
  1835.                 if (pipe_error)                        /* pipe create failed */
  1836.                 {
  1837.                     close(fd_toshell[0]);
  1838.                     close(fd_toshell[1]);
  1839.                 }
  1840.             }
  1841.             if (pipe_error)
  1842.             {
  1843.                 MSG_OUTSTR("\nCannot create pipes\n");
  1844.                 flushbuf();
  1845.             }
  1846.         }
  1847.     }
  1848.  
  1849.     if (!pipe_error)                    /* pty or pipe opened or not used */
  1850. #endif
  1851.  
  1852.     {
  1853.         if ((pid = fork()) == -1)        /* maybe we should use vfork() */
  1854.         {
  1855.             MSG_OUTSTR("\nCannot fork\n");
  1856. #ifdef USE_GUI
  1857.             if (gui.in_use && show_shell_mess)
  1858.             {
  1859.                 if (pty_master_fd >= 0)            /* close the pseudo tty */
  1860.                 {
  1861.                     close(pty_master_fd);
  1862.                     close(pty_slave_fd);
  1863.                 }
  1864.                 else                            /* close the pipes */
  1865.                 {
  1866.                     close(fd_toshell[0]);
  1867.                     close(fd_toshell[1]);
  1868.                     close(fd_fromshell[0]);
  1869.                     close(fd_fromshell[1]);
  1870.                 }
  1871.             }
  1872. #endif
  1873.         }
  1874.         else if (pid == 0)        /* child */
  1875.         {
  1876.             reset_signals();            /* handle signals normally */
  1877.             if (!show_shell_mess)
  1878.             {
  1879.                 int fd;
  1880.  
  1881.                 /*
  1882.                  * Don't want to show any message from the shell.  Can't just
  1883.                  * close stdout and stderr though, because some systems will
  1884.                  * break if you try to write to them after that, so we must
  1885.                  * use dup() to replace them with something else -- webb
  1886.                  */
  1887.                 fd = open("/dev/null", O_WRONLY | O_EXTRA);
  1888.                 fclose(stdout);
  1889.                 fclose(stderr);
  1890.  
  1891.                 /*
  1892.                  * If any of these open()'s and dup()'s fail, we just continue
  1893.                  * anyway.  It's not fatal, and on most systems it will make
  1894.                  * no difference at all.  On a few it will cause the execvp()
  1895.                  * to exit with a non-zero status even when the completion
  1896.                  * could be done, which is nothing too serious.  If the open()
  1897.                  * or dup() failed we'd just do the same thing ourselves
  1898.                  * anyway -- webb
  1899.                  */
  1900.                 if (fd >= 0)
  1901.                 {
  1902.                     /* To replace stdout (file descriptor 1) */
  1903.                     dup(fd);
  1904.  
  1905.                     /* To replace stderr (file descriptor 2) */
  1906.                     dup(fd);
  1907.  
  1908.                     /* Don't need this now that we've duplicated it */
  1909.                     close(fd);
  1910.                 }
  1911.             }
  1912. #ifdef USE_GUI
  1913.             else if (gui.in_use)
  1914.             {
  1915.  
  1916. #ifdef HAVE_SETSID
  1917.                 (void)setsid();
  1918. #endif
  1919. #ifdef TIOCSCTTY
  1920.                 /* try to become controlling tty (probably doesn't work,
  1921.                  * unless run by root) */
  1922.                 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
  1923. #endif
  1924.                 /* Simulate to have a dumb terminal (for now) */
  1925. #ifdef HAVE_SETENV
  1926.                 setenv("TERM", "dumb", 1);
  1927.                 sprintf((char *)envbuf, "%ld", Rows);
  1928.                 setenv("ROWS", (char *)envbuf, 1);
  1929.                 sprintf((char *)envbuf, "%ld", Columns);
  1930.                 setenv("COLUMNS", (char *)envbuf, 1);
  1931. #else
  1932.                 /*
  1933.                  * Putenv does not copy the string, it has to remain valid.
  1934.                  * Use a static array to avoid loosing allocated memory.
  1935.                  */
  1936.                 putenv("TERM=dumb");
  1937.                 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
  1938.                 putenv(envbuf_Rows);
  1939.                 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
  1940.                 putenv(envbuf_Columns);
  1941. #endif
  1942.  
  1943.                 if (pty_master_fd >= 0)
  1944.                 {
  1945.                     close(pty_master_fd);    /* close master side of pty */
  1946.  
  1947.                     /* set up stdin/stdout/stderr for the child */
  1948.                     close(0);
  1949.                     dup(pty_slave_fd);
  1950.                     close(1);
  1951.                     dup(pty_slave_fd);
  1952.                     close(2);
  1953.                     dup(pty_slave_fd);
  1954.  
  1955.                     close(pty_slave_fd);    /* has been dupped, close it now */
  1956.                 }
  1957.                 else
  1958.                 {
  1959.                     /* set up stdin for the child */
  1960.                     close(fd_toshell[1]);
  1961.                     close(0);
  1962.                     dup(fd_toshell[0]);
  1963.                     close(fd_toshell[0]);
  1964.  
  1965.                     /* set up stdout for the child */
  1966.                     close(fd_fromshell[0]);
  1967.                     close(1);
  1968.                     dup(fd_fromshell[1]);
  1969.                     close(fd_fromshell[1]);
  1970.  
  1971.                     /* set up stderr for the child */
  1972.                     close(2);
  1973.                     dup(1);
  1974.                 }
  1975.             }
  1976. #endif
  1977.             /*
  1978.              * There is no type cast for the argv, because the type may be
  1979.              * different on different machines. This may cause a warning
  1980.              * message with strict compilers, don't worry about it.
  1981.              */
  1982.             execvp(argv[0], argv);
  1983.             exit(EXEC_FAILED);        /* exec failed, return failure code */
  1984.         }
  1985.         else                    /* parent */
  1986.         {
  1987.             /*
  1988.              * While child is running, ignore terminating signals.
  1989.              */
  1990.             catch_signals(SIG_IGN);
  1991.  
  1992. #ifdef USE_GUI
  1993.  
  1994.             /*
  1995.              * For the GUI we redirect stdin, stdout and stderr to our window.
  1996.              */
  1997.             if (gui.in_use && show_shell_mess)
  1998.             {
  1999. #define BUFLEN 100                /* length for buffer, pseudo tty limit is 128 */
  2000.                 char_u        buffer[BUFLEN];
  2001.                 int            len;
  2002.                 int            p_more_save;
  2003.                 int            old_State;
  2004.                 int            read_count;
  2005.                 int            c;
  2006.                 int            toshell_fd;
  2007.                 int            fromshell_fd;
  2008.  
  2009.                 if (pty_master_fd >= 0)
  2010.                 {
  2011.                     close(pty_slave_fd);        /* close slave side of pty */
  2012.                     fromshell_fd = pty_master_fd;
  2013.                     toshell_fd = dup(pty_master_fd);
  2014.                 }
  2015.                 else
  2016.                 {
  2017.                     close(fd_toshell[0]);
  2018.                     close(fd_fromshell[1]);
  2019.                     toshell_fd = fd_toshell[1];
  2020.                     fromshell_fd = fd_fromshell[0];
  2021.                 }
  2022.  
  2023.                 /*
  2024.                  * Write to the child if there are typed characters.
  2025.                  * Read from the child if there are characters available.
  2026.                  *   Repeat the reading a few times if more characters are
  2027.                  *   available. Need to check for typed keys now and then, but
  2028.                  *   not too often (delays when no chars are available).
  2029.                  * This loop is quit if no characters can be read from the pty
  2030.                  * (WaitForChar detected special condition), or there are no
  2031.                  * characters available and the child has exited.
  2032.                  * Only check if the child has exited when there is no more
  2033.                  * output. The child may exit before all the output has
  2034.                  * been printed.
  2035.                  *
  2036.                  * Currently this busy loops!
  2037.                  * This can probably dead-lock when the write blocks!
  2038.                  */
  2039.                 p_more_save = p_more;
  2040.                 p_more = FALSE;
  2041.                 old_State = State;
  2042.                 State = EXTERNCMD;        /* don't redraw at window resize */
  2043.  
  2044.                 for (;;)
  2045.                 {
  2046.                     /*
  2047.                      * Check if keys have been typed, write them to the child
  2048.                      * if there are any.  Don't do this if we are expanding
  2049.                      * wild cards (would eat typeahead).
  2050.                      */
  2051.                     if (!(options & SHELL_EXPAND) &&
  2052.                               (len = mch_inchar(buffer, BUFLEN - 1, 10)) != 0)
  2053.                     {
  2054.                         /*
  2055.                          * For pipes:
  2056.                          * Check for CTRL-C: sent interrupt signal to child.
  2057.                          * Check for CTRL-D: EOF, close pipe to child.
  2058.                          */
  2059.                         if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
  2060.                         {
  2061. #ifdef SIGINT
  2062.                             if (buffer[0] == Ctrl('C'))
  2063.                             {
  2064.                                 /* Use both kill() and killpg(), in case one
  2065.                                  * of the two fails */
  2066.                                 kill(pid, SIGINT);
  2067. # ifdef HAVE_KILLPG
  2068.                                 killpg(0, SIGINT);
  2069. # endif
  2070.                             }
  2071. #endif
  2072.                             if (pty_master_fd < 0 && toshell_fd >= 0 &&
  2073.                                                        buffer[0] == Ctrl('D'))
  2074.                             {
  2075.                                 close(toshell_fd);
  2076.                                 toshell_fd = -1;
  2077.                             }
  2078.                         }
  2079.  
  2080.                         /* replace K_BS by <BS> and K_DEL by <DEL> */
  2081.                         for (i = 0; i < len; ++i)
  2082.                         {
  2083.                             if (buffer[i] == CSI && len - i > 2)
  2084.                             {
  2085.                                 c = TERMCAP2KEY(buffer[i + 1], buffer[i + 2]);
  2086.                                 if (c == K_DEL || c == K_BS)
  2087.                                 {
  2088.                                     vim_memmove(buffer + i + 1, buffer + i + 3,
  2089.                                                        (size_t)(len - i - 2));
  2090.                                     if (c == K_DEL)
  2091.                                         buffer[i] = DEL;
  2092.                                     else
  2093.                                         buffer[i] = Ctrl('H');
  2094.                                     len -= 2;
  2095.                                 }
  2096.                             }
  2097.                             else if (buffer[i] == '\r')
  2098.                                 buffer[i] = '\n';
  2099.                         }
  2100.  
  2101.                         /*
  2102.                          * For pipes: echo the typed characters.
  2103.                          * For a pty this does not seem to work.
  2104.                          */
  2105.                         if (pty_master_fd < 0)
  2106.                         {
  2107.                             for (i = 0; i < len; ++i)
  2108.                                 if (buffer[i] == '\n' || buffer[i] == '\b')
  2109.                                     msg_outchar(buffer[i]);
  2110.                                 else
  2111.                                     msg_outtrans_len(buffer + i, 1);
  2112.                             windgoto(msg_row, msg_col);
  2113.                             flushbuf();
  2114.                         }
  2115.  
  2116.                         /*
  2117.                          * Write the characters to the child, unless EOF has
  2118.                          * been typed for pipes.  Ignore errors.
  2119.                          */
  2120.                         if (toshell_fd >= 0)
  2121.                             write(toshell_fd, (char *)buffer, (size_t)len);
  2122.                     }
  2123.  
  2124.                     /*
  2125.                      * Check if the child has any characters to be printed.
  2126.                      * Read them and write them to our window.
  2127.                      * Repeat this a few times as long as there is something
  2128.                      * to do, avoid the 10ms wait for mch_inchar().
  2129.                      * TODO: This should handle escape sequences.
  2130.                      */
  2131.                     for (read_count = 0; read_count < 10 &&
  2132.                              RealWaitForChar(fromshell_fd, 10); ++read_count)
  2133.                     {
  2134.                         len = read(fromshell_fd, (char *)buffer,
  2135.                                                               (size_t)BUFLEN);
  2136.                         if (len == 0)                /* end of file */
  2137.                             goto finished;
  2138.                         buffer[len] = NUL;
  2139.                         msg_outstr(buffer);
  2140.                         windgoto(msg_row, msg_col);
  2141.                         cursor_on();
  2142.                         flushbuf();
  2143.                     }
  2144.  
  2145.                     /*
  2146.                      * Check if the child still exists when we finished
  2147.                      * outputting all characters.
  2148.                      */
  2149.                     if (read_count == 0 &&
  2150. #ifdef __NeXT__
  2151.                             wait4(pid, &status, WNOHANG, (struct rusage *) 0) &&
  2152. #else
  2153.                             waitpid(pid, &status, WNOHANG) &&
  2154. #endif
  2155.                                                             WIFEXITED(status))
  2156.                         break;
  2157.                 }
  2158. finished:
  2159.                 p_more = p_more_save;
  2160.                 State = old_State;
  2161.                 if (toshell_fd >= 0)
  2162.                     close(toshell_fd);
  2163.                 close(fromshell_fd);
  2164.             }
  2165. #endif /* USE_GUI */
  2166.  
  2167.             /*
  2168.              * Wait until child has exited.
  2169.              */
  2170. #ifdef ECHILD
  2171.             /* Don't stop waiting when a signal (e.g. SIGWINCH) is received. */
  2172.             while (wait(&status) == -1 && errno != ECHILD)
  2173.                 ;
  2174. #else
  2175.             wait(&status);
  2176. #endif
  2177.             /*
  2178.              * Set to raw mode right now, otherwise a CTRL-C after
  2179.              * catch_signals will kill Vim.
  2180.              */
  2181.             settmode(1);
  2182.             did_settmode = TRUE;
  2183.             catch_signals(deathtrap);
  2184.  
  2185.             /*
  2186.              * Check the window size, in case it changed while executing the
  2187.              * external command.
  2188.              */
  2189.             mch_get_winsize();
  2190.  
  2191.             if (WIFEXITED(status))
  2192.             {
  2193.                 i = WEXITSTATUS(status);
  2194.                 if (i)
  2195.                 {
  2196.                     if (i == EXEC_FAILED)
  2197.                     {
  2198.                         MSG_OUTSTR("\nCannot execute shell ");
  2199.                         msg_outtrans(p_sh);
  2200.                         msg_outchar('\n');
  2201.                     }
  2202.                     else if (!expand_interactively)
  2203.                     {
  2204.                         msg_outchar('\n');
  2205.                         msg_outnum((long)i);
  2206.                         MSG_OUTSTR(" returned\n");
  2207.                     }
  2208.                 }
  2209.                 else
  2210.                     retval = OK;
  2211.             }
  2212.             else
  2213.                 MSG_OUTSTR("\nCommand terminated\n");
  2214.         }
  2215.     }
  2216.     vim_free(argv);
  2217.  
  2218. error:
  2219.     if (!did_settmode)
  2220.         settmode(1);                         /* always set to raw mode */
  2221.     resettitle();
  2222.  
  2223.     return retval;
  2224.  
  2225. #endif /* USE_SYSTEM */
  2226. }
  2227.  
  2228. /*
  2229.  * The input characters are buffered to be able to check for a CTRL-C.
  2230.  * This should be done with signals, but I don't know how to do that in
  2231.  * a portable way for a tty in RAW mode.
  2232.  */
  2233.  
  2234. /*
  2235.  * Internal typeahead buffer.  Includes extra space for long key code
  2236.  * descriptions which would otherwise overflow.  The buffer is considered full
  2237.  * when only this extra space (or part of it) remains.
  2238.  */
  2239. #define INBUFLEN 250
  2240.  
  2241. static char_u    inbuf[INBUFLEN + MAX_KEY_CODE_LEN];
  2242. static int        inbufcount = 0;        /* number of chars in inbuf[] */
  2243.  
  2244. /*
  2245.  * is_input_buf_full(), is_input_buf_empty(), add_to_input_buf(), and
  2246.  * trash_input_buf() are functions for manipulating the input buffer.  These
  2247.  * are used by the gui_* calls when a GUI is used to handle keyboard input.
  2248.  *
  2249.  * NOTE: These functions will be identical in msdos.c etc, and should probably
  2250.  * be taken out and put elsewhere, but at the moment inbuf is only local.
  2251.  */
  2252.  
  2253.     int
  2254. is_input_buf_full()
  2255. {
  2256.     return (inbufcount >= INBUFLEN);
  2257. }
  2258.  
  2259.     int
  2260. is_input_buf_empty()
  2261. {
  2262.     return (inbufcount == 0);
  2263. }
  2264.  
  2265. /* Add the given bytes to the input buffer */
  2266.     void
  2267. add_to_input_buf(s, len)
  2268.     char_u    *s;
  2269.     int        len;
  2270. {
  2271.     if (inbufcount + len > INBUFLEN + MAX_KEY_CODE_LEN)
  2272.         return;        /* Shouldn't ever happen! */
  2273.     
  2274.     while (len--)
  2275.         inbuf[inbufcount++] = *s++;
  2276. }
  2277.  
  2278. /* Remove everything from the input buffer.  Called when ^C is found */
  2279.     void
  2280. trash_input_buf()
  2281. {
  2282.     inbufcount = 0;
  2283. }
  2284.  
  2285.     static int
  2286. Read(buf, maxlen)
  2287.     char_u    *buf;
  2288.     long    maxlen;
  2289. {
  2290.     if (inbufcount == 0)        /* if the buffer is empty, fill it */
  2291.         fill_inbuf(TRUE);
  2292.     if (maxlen > inbufcount)
  2293.         maxlen = inbufcount;
  2294.     vim_memmove(buf, inbuf, (size_t)maxlen);
  2295.     inbufcount -= maxlen;
  2296.     if (inbufcount)
  2297.         vim_memmove(inbuf, inbuf + maxlen, (size_t)inbufcount);
  2298.     return (int)maxlen;
  2299. }
  2300.  
  2301.     void
  2302. mch_breakcheck()
  2303. {
  2304. #ifdef USE_GUI
  2305.     if (gui.in_use)
  2306.     {
  2307.         gui_mch_update();
  2308.         return;
  2309.     }
  2310. #endif /* USE_GUI */
  2311.  
  2312. /*
  2313.  * Check for CTRL-C typed by reading all available characters.
  2314.  * In cooked mode we should get SIGINT, no need to check.
  2315.  */
  2316.     if (curr_tmode && RealWaitForChar(0, 0L))    /* if characters available */
  2317.         fill_inbuf(FALSE);
  2318. }
  2319.  
  2320.     static void
  2321. fill_inbuf(exit_on_error)
  2322.     int    exit_on_error;
  2323. {
  2324.     int        len;
  2325.     int        try;
  2326.  
  2327. #ifdef USE_GUI
  2328.     if (gui.in_use)
  2329.     {
  2330.         gui_mch_update();
  2331.         return;
  2332.     }
  2333. #endif
  2334.     if (is_input_buf_full())
  2335.         return;
  2336.     /*
  2337.      * Fill_inbuf() is only called when we really need a character.
  2338.      * If we can't get any, but there is some in the buffer, just return.
  2339.      * If we can't get any, and there isn't any in the buffer, we give up and
  2340.      * exit Vim.
  2341.      */
  2342.     for (try = 0; try < 100; ++try)
  2343.     {
  2344.         len = read(0, (char *)inbuf + inbufcount,
  2345.                                              (size_t)(INBUFLEN - inbufcount));
  2346.         if (len > 0)
  2347.             break;
  2348.         if (!exit_on_error)
  2349.             return;
  2350.     }
  2351.     if (len <= 0)
  2352.     {
  2353.         windgoto((int)Rows - 1, 0);
  2354.         fprintf(stderr, "Vim: Error reading input, exiting...\n");
  2355.         ml_sync_all(FALSE, TRUE);        /* preserve all swap files */
  2356.         getout(1);
  2357.     }
  2358.     while (len-- > 0)
  2359.     {
  2360.         /*
  2361.          * if a CTRL-C was typed, remove it from the buffer and set got_int
  2362.          */
  2363.         if (inbuf[inbufcount] == 3)
  2364.         {
  2365.             /* remove everything typed before the CTRL-C */
  2366.             vim_memmove(inbuf, inbuf + inbufcount, (size_t)(len + 1));
  2367.             inbufcount = 0;
  2368.             got_int = TRUE;
  2369.         }
  2370.         ++inbufcount;
  2371.     }
  2372. }
  2373.  
  2374. /* 
  2375.  * Wait "msec" msec until a character is available from the keyboard or from
  2376.  * inbuf[]. msec == -1 will block forever.
  2377.  * When a GUI is being used, this will never get called -- webb 
  2378.  */
  2379.  
  2380.     static    int
  2381. WaitForChar(msec)
  2382.     long    msec;
  2383. {
  2384.     if (inbufcount)        /* something in inbuf[] */
  2385.         return 1;
  2386.     return RealWaitForChar(0, msec);
  2387. }
  2388.  
  2389. /* 
  2390.  * Wait "msec" msec until a character is available from file descriptor "fd".
  2391.  * Time == -1 will block forever.
  2392.  * When a GUI is being used, this will not be used for input -- webb 
  2393.  */
  2394.     static    int
  2395. RealWaitForChar(fd, msec)
  2396.     int        fd;
  2397.     long    msec;
  2398. {
  2399. #ifndef HAVE_SELECT
  2400.     struct pollfd fds;
  2401.  
  2402.     fds.fd = fd;
  2403.     fds.events = POLLIN;
  2404.     return (poll(&fds, 1, (int)msec) > 0);    /* is this correct when fd != 0?? */
  2405. #else
  2406.     struct timeval tv;
  2407.     fd_set rfds, efds;
  2408.  
  2409. # ifdef __EMX__
  2410.     /* don't check for incoming chars if not in raw mode, because select()
  2411.      * always returns TRUE then (in some version of emx.dll) */
  2412.     if (curr_tmode == 0)
  2413.         return 0;
  2414. # endif
  2415.  
  2416.     if (msec >= 0)
  2417.     {
  2418.            tv.tv_sec = msec / 1000;
  2419.         tv.tv_usec = (msec % 1000) * (1000000/1000);
  2420.     }
  2421.  
  2422.     /*
  2423.      * Select on ready for reading and exceptional condition (end of file).
  2424.      */
  2425.     FD_ZERO(&rfds);    /* calls bzero() on a sun */
  2426.     FD_ZERO(&efds);
  2427.     FD_SET(fd, &rfds);
  2428.     FD_SET(fd, &efds);
  2429.     return (select(fd + 1, &rfds, NULL, &efds, (msec >= 0) ? &tv : NULL) > 0);
  2430. #endif
  2431. }
  2432.  
  2433. /*
  2434.  * ExpandWildCards() - this code does wild-card pattern matching using the shell
  2435.  *
  2436.  * return OK for success, FAIL for error (you may lose some memory) and put
  2437.  * an error message in *file.
  2438.  *
  2439.  * num_pat is number of input patterns
  2440.  * pat is array of pointers to input patterns
  2441.  * num_file is pointer to number of matched file names
  2442.  * file is pointer to array of pointers to matched file names
  2443.  * On Unix we do not check for files only yet
  2444.  * list_notfound is ignored
  2445.  */
  2446.  
  2447. extern char *mktemp __ARGS((char *));
  2448. #ifndef SEEK_SET
  2449. # define SEEK_SET 0
  2450. #endif
  2451. #ifndef SEEK_END
  2452. # define SEEK_END 2
  2453. #endif
  2454.  
  2455.     int
  2456. ExpandWildCards(num_pat, pat, num_file, file, files_only, list_notfound)
  2457.     int             num_pat;
  2458.     char_u          **pat;
  2459.     int            *num_file;
  2460.     char_u         ***file;
  2461.     int                files_only;
  2462.     int                list_notfound;
  2463. {
  2464.     int        i;
  2465.     size_t    len;
  2466.     char_u    *p;
  2467. #ifdef __EMX__
  2468. # define EXPL_ALLOC_INC    16
  2469.     char_u    **expl_files;
  2470.     size_t    files_alloced, files_free;
  2471.  
  2472.     *num_file = 0;        /* default: no files found */
  2473.     files_alloced = EXPL_ALLOC_INC;    /* how much space is allocated */
  2474.     files_free = EXPL_ALLOC_INC;    /* how much space is not used  */
  2475.     *file = (char_u **) alloc(sizeof(char_u **) * files_alloced);
  2476.     if (!*file)
  2477.     {
  2478.         emsg(e_outofmem);
  2479.         return FAIL;
  2480.     }
  2481.  
  2482.     for (; num_pat > 0; num_pat--, pat++)
  2483.     {
  2484.         expl_files = NULL;
  2485.         if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
  2486.         {
  2487.             /* expand environment var or home dir */
  2488.             char_u    *buf = alloc(1024);
  2489.             if (!buf)
  2490.             {
  2491.                 emsg(e_outofmem);
  2492.                 return FAIL;
  2493.             }
  2494.             expand_env(*pat, buf, 1024);
  2495.             if (mch_has_wildcard(buf))    /* still wildcards in there? */
  2496.             {
  2497.                 expl_files = (char_u **)_fnexplode(buf);
  2498.             }
  2499.             if (expl_files == NULL)
  2500.             {
  2501.                 /*
  2502.                  * If no wildcard still remaining, simply add
  2503.                  * the pattern to the results.
  2504.                  * If wildcard did not match, add the pattern to
  2505.                  * the list of results anyway. This way, doing
  2506.                  * :n exist.c notexist*
  2507.                  * will at least edits exist.c and then say
  2508.                  * notexist* [new file]
  2509.                  */
  2510.                 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
  2511.                 expl_files[0] = strsave(buf);
  2512.                 expl_files[1] = NULL;
  2513.             }
  2514.             vim_free(buf);
  2515.         }
  2516.         else
  2517.         {
  2518.             expl_files = (char_u **)_fnexplode(*pat);
  2519.             if (expl_files == NULL)
  2520.             {
  2521.                 /* see above for explanation */
  2522.                 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
  2523.                 expl_files[0] = strsave(*pat);
  2524.                 expl_files[1] = NULL;
  2525.             }
  2526.         }
  2527.         if (!expl_files)
  2528.         {
  2529.             /* Can't happen */
  2530.             char_u msg[128];
  2531.             sprintf(msg, "%s (unix.c:%d)", e_internal, __LINE__);
  2532.             emsg(msg);
  2533.             *file = (char_u **)"";
  2534.             *num_file = 0;
  2535.             return OK;
  2536.         }
  2537.         /*
  2538.          * Count number of names resulting from expansion,
  2539.          * At the same time add a backslash to the end of names that happen to be
  2540.          * directories, and replace slashes with backslashes.
  2541.          */
  2542.         for (i = 0; (p = expl_files[i]) != NULL; i++, (*num_file)++)
  2543.         {
  2544.             if (--files_free == 0)
  2545.             {
  2546.                 /* need more room in table of pointers */
  2547.                 files_alloced += EXPL_ALLOC_INC;
  2548.                 *file = (char_u **) realloc(*file,
  2549.                                             sizeof(char_u **) * files_alloced);
  2550.                 files_free = EXPL_ALLOC_INC;
  2551.             }
  2552.             slash_adjust(p);
  2553.             if (mch_isdir(p))
  2554.             {
  2555.                 len = strlen(p);
  2556.                 p = realloc(p, len + 2);
  2557.                 if (!p)
  2558.                 {
  2559.                     emsg(e_outofmem);
  2560.                     return FAIL;
  2561.                 }
  2562.                 (*file)[*num_file] = p;
  2563.                 p += len;
  2564.                 *p++ = '\\';
  2565.                 *p = 0;
  2566.             }
  2567.             else
  2568.             {
  2569.                 (*file)[*num_file] = strsave(p);
  2570.             }
  2571.         }
  2572.         _fnexplodefree(expl_files);
  2573.     }
  2574.     return OK;
  2575.  
  2576. #else /* __EMX__ */
  2577.  
  2578.     int        dir;
  2579.     char_u    tmpname[TMPNAMELEN];
  2580.     char_u    *command;
  2581.     FILE    *fd;
  2582.     char_u    *buffer;
  2583.     int        use_glob = FALSE;
  2584.  
  2585.     *num_file = 0;        /* default: no files found */
  2586.     *file = (char_u **)"";
  2587.  
  2588.     /*
  2589.      * If there are no wildcards, just copy the names to allocated memory.
  2590.      * Saves a lot of time, because we don't have to start a new shell.
  2591.      */
  2592.     if (!have_wildcard(num_pat, pat))
  2593.     {
  2594.         *file = (char_u **)alloc(num_pat * sizeof(char_u *));
  2595.         if (*file == NULL)
  2596.         {
  2597.             *file = (char_u **)"";
  2598.             return FAIL;
  2599.         }
  2600.         for (i = 0; i < num_pat; i++)
  2601.             (*file)[i] = strsave(pat[i]);
  2602.         *num_file = num_pat;
  2603.         return OK;
  2604.     }
  2605.  
  2606. /*
  2607.  * get a name for the temp file
  2608.  */
  2609.     STRCPY(tmpname, TMPNAME2);
  2610.     if (*mktemp((char *)tmpname) == NUL)
  2611.     {
  2612.         emsg(e_notmp);
  2613.         return FAIL;
  2614.     }
  2615.  
  2616. /*
  2617.  * let the shell expand the patterns and write the result into the temp file
  2618.  * If we use csh, glob will work better than echo.
  2619.  */
  2620.     if ((len = STRLEN(p_sh)) >= 3 && STRCMP(p_sh + len - 3, "csh") == 0)
  2621.         use_glob = TRUE;
  2622.  
  2623.     len = TMPNAMELEN + 11;
  2624.     for (i = 0; i < num_pat; ++i)        /* count the length of the patterns */
  2625.         len += STRLEN(pat[i]) + 3;
  2626.     command = alloc(len);
  2627.     if (command == NULL)
  2628.         return FAIL;
  2629.     if (use_glob)
  2630.         STRCPY(command, "glob >");        /* build the shell command */
  2631.     else
  2632.         STRCPY(command, "echo >");        /* build the shell command */
  2633.     STRCAT(command, tmpname);
  2634.     for (i = 0; i < num_pat; ++i)
  2635.     {
  2636. #ifdef USE_SYSTEM
  2637.         STRCAT(command, " \"");                /* need extra quotes because we */
  2638.         STRCAT(command, pat[i]);            /*   start the shell twice */
  2639.         STRCAT(command, "\"");
  2640. #else
  2641.         STRCAT(command, " ");
  2642.         STRCAT(command, pat[i]);
  2643. #endif
  2644.     }
  2645.     if (expand_interactively)
  2646.         show_shell_mess = FALSE;
  2647.     /*
  2648.      * If we use -f then shell variables set in .cshrc won't get expanded.
  2649.      * vi can do it, so we will too, but it is only necessary if there is a "$"
  2650.      * in one of the patterns, otherwise we can still use the fast option.
  2651.      */
  2652.     if (use_glob && !have_dollars(num_pat, pat))    /* Use csh fast option */
  2653.         extra_shell_arg = (char_u *)"-f";
  2654.     i = call_shell(command, SHELL_EXPAND);        /* execute it */
  2655.     extra_shell_arg = NULL;
  2656.     show_shell_mess = TRUE;
  2657.     vim_free(command);
  2658.     if (i == FAIL)                            /* call_shell failed */
  2659.     {
  2660.         vim_remove(tmpname);
  2661.         /*
  2662.          * With interactive completion, the error message is not printed.
  2663.          * However with USE_SYSTEM, I don't know how to turn off error messages
  2664.          * from the shell, so screen may still get messed up -- webb.
  2665.          */
  2666. #ifndef USE_SYSTEM
  2667.         if (!expand_interactively)
  2668. #endif
  2669.         {
  2670.             must_redraw = CLEAR;            /* probably messed up screen */
  2671.             msg_outchar('\n');                /* clear bottom line quickly */
  2672.             cmdline_row = Rows - 1;            /* continue on last line */
  2673.         }
  2674.         return FAIL;
  2675.     }
  2676.  
  2677. /*
  2678.  * read the names from the file into memory
  2679.  */
  2680.      fd = fopen((char *)tmpname, "r");
  2681.     if (fd == NULL)
  2682.     {
  2683.         emsg2(e_notopen, tmpname);
  2684.         return FAIL;
  2685.     }
  2686.     fseek(fd, 0L, SEEK_END);
  2687.     len = ftell(fd);                /* get size of temp file */
  2688.     fseek(fd, 0L, SEEK_SET);
  2689.     buffer = alloc(len + 1);
  2690.     if (buffer == NULL)
  2691.     {
  2692.         vim_remove(tmpname);
  2693.         fclose(fd);
  2694.         return FAIL;
  2695.     }
  2696.     i = fread((char *)buffer, 1, len, fd);
  2697.     fclose(fd);
  2698.     vim_remove(tmpname);
  2699.     if (i != len)
  2700.     {
  2701.         emsg2(e_notread, tmpname);
  2702.         vim_free(buffer);
  2703.         return FAIL;
  2704.     }
  2705.  
  2706.     if (use_glob)        /* file names are separated with NUL */
  2707.     {
  2708.         buffer[len] = NUL;                /* make sure the buffers ends in NUL */
  2709.         i = 0;
  2710.         for (p = buffer; p < buffer + len; ++p)
  2711.             if (*p == NUL)                /* count entry */
  2712.                 ++i;
  2713.         if (len)
  2714.             ++i;                        /* count last entry */
  2715.     }
  2716.     else                /* file names are separated with SPACE */
  2717.     {
  2718.         buffer[len] = '\n';                /* make sure the buffers ends in NL */
  2719.         p = buffer;
  2720.         for (i = 0; *p != '\n'; ++i)    /* count number of entries */
  2721.         {
  2722.             while (*p != ' ' && *p != '\n')    /* skip entry */
  2723.                 ++p;
  2724.             p = skipwhite(p);            /* skip to next entry */
  2725.         }
  2726.     }
  2727.     if (i == 0)
  2728.     {
  2729.         /*
  2730.          * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
  2731.          * /bin/sh will happily expand it to nothing rather than returning an
  2732.          * error; and hey, it's good to check anyway -- webb.
  2733.          */
  2734.         vim_free(buffer);
  2735.         *file = (char_u **)"";
  2736.         return FAIL;
  2737.     }
  2738.     *num_file = i;
  2739.     *file = (char_u **)alloc(sizeof(char_u *) * i);
  2740.     if (*file == NULL)
  2741.     {
  2742.         vim_free(buffer);
  2743.         *file = (char_u **)"";
  2744.         return FAIL;
  2745.     }
  2746.     
  2747.     /*
  2748.      * Isolate the individual file names.
  2749.      */
  2750.     p = buffer;
  2751.     for (i = 0; i < *num_file; ++i)
  2752.     {
  2753.         (*file)[i] = p;
  2754.         if (use_glob)
  2755.         {
  2756.             while (*p && p < buffer + len)        /* skip entry */
  2757.                 ++p;
  2758.             ++p;                                /* skip NUL */
  2759.         }
  2760.         else
  2761.         {
  2762.             while (*p != ' ' && *p != '\n')        /* skip entry */
  2763.                 ++p;
  2764.             if (*p == '\n')                        /* last entry */
  2765.                 *p = NUL;
  2766.             else
  2767.             {
  2768.                 *p++ = NUL;
  2769.                 p = skipwhite(p);                /* skip to next entry */
  2770.             }
  2771.         }
  2772.     }
  2773.  
  2774.     /*
  2775.      * Move the file names to allocated memory.
  2776.      */
  2777.     for (i = 0; i < *num_file; ++i)
  2778.     {
  2779.         /* Require the files to exist.  Helps when using /bin/sh */
  2780.         if (expand_interactively)
  2781.         {
  2782.             struct stat        st;
  2783.             int                j;
  2784.  
  2785.             if (stat((char *)((*file)[i]), &st) < 0)
  2786.             {
  2787.                 for (j = i; j + 1 < *num_file; ++j)
  2788.                     (*file)[j] = (*file)[j + 1];
  2789.                 --*num_file;
  2790.                 --i;
  2791.                 continue;
  2792.             }
  2793.         }
  2794.  
  2795.         /* if file doesn't exist don't add '/' */
  2796.         dir = (mch_isdir((*file)[i]));
  2797.         p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
  2798.         if (p)
  2799.         {
  2800.             STRCPY(p, (*file)[i]);
  2801.             if (dir)
  2802.                 STRCAT(p, "/");
  2803.         }
  2804.         (*file)[i] = p;
  2805.     }
  2806.     vim_free(buffer);
  2807.  
  2808.     if (*num_file == 0)        /* rejected all entries */
  2809.     {
  2810.         vim_free(*file);
  2811.         *file = (char_u **)"";
  2812.         return FAIL;
  2813.     }
  2814.  
  2815.     return OK;
  2816.  
  2817. #endif /* __EMX__ */
  2818. }
  2819.  
  2820.     int
  2821. mch_has_wildcard(p)
  2822.     char_u    *p;
  2823. {
  2824.     for ( ; *p; ++p)
  2825.     {
  2826.         if (*p == '\\' && p[1] != NUL)
  2827.             ++p;
  2828.         else if (vim_strchr((char_u *)"*?[{`~$", *p) != NULL)
  2829.             return TRUE;
  2830.     }
  2831.     return FALSE;
  2832. }
  2833.  
  2834. #ifndef __EMX__
  2835.     static int
  2836. have_wildcard(num, file)
  2837.     int        num;
  2838.     char_u    **file;
  2839. {
  2840.     register int i;
  2841.  
  2842.     for (i = 0; i < num; i++)
  2843.         if (mch_has_wildcard(file[i]))
  2844.             return 1;
  2845.     return 0;
  2846. }
  2847.  
  2848.     static int
  2849. have_dollars(num, file)
  2850.     int        num;
  2851.     char_u    **file;
  2852. {
  2853.     register int i;
  2854.  
  2855.     for (i = 0; i < num; i++)
  2856.         if (vim_strchr(file[i], '$') != NULL)
  2857.             return TRUE;
  2858.     return FALSE;
  2859. }
  2860. #endif    /* ifndef __EMX__ */
  2861.  
  2862. #ifndef HAVE_RENAME
  2863. /*
  2864.  * Scaled-down version of rename, which is missing in Xenix.
  2865.  * This version can only move regular files and will fail if the
  2866.  * destination exists.
  2867.  */
  2868.     int
  2869. rename(src, dest)
  2870.     const char *src, *dest;
  2871. {
  2872.     struct stat        st;
  2873.  
  2874.     if (stat(dest, &st) >= 0)        /* fail if destination exists */
  2875.         return -1;
  2876.     if (link(src, dest) != 0)        /* link file to new name */
  2877.         return -1;
  2878.     if (vim_remove(src) == 0)        /* delete link to old name */
  2879.         return 0;
  2880.     return -1;
  2881. }
  2882. #endif /* !HAVE_RENAME */
  2883.